<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\admin;

use buwang\base\AdminBaseController;
use buwang\service\PluginService;
use buwang\traits\CrudControllerTrait;
use think\facade\Cache;
use think\facade\View;

/**
 * 插件
 * @menu true
 * Class Plugin
 * @package app\manage\controller\admin
 */
class Plugin extends AdminBaseController
{
    use CrudControllerTrait;

    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();
        $this->model = new \app\manage\model\admin\Plugin();
    }

    /**
     * 查看
     * @menu true
     */
    public function index()
    {
        if (request()->isAjax()) {
            //取得模块目录名称
            $dirs = array_map('basename', glob(ADDON_PATH . '*', GLOB_ONLYDIR));
            if ($dirs === false || !file_exists(ADDON_PATH)) return $this->error('插件目录不可读或者不存在');
            // 读取数据库插件表
            $addons = $this->model->order('id asc')->column('*', 'name');
            //TODO 清除插件列表缓存【后期加上清除插件缓存按钮】
            Cache::has('addonslist') && Cache::delete('addonslist');
            $dir_addons_list = get_addons_list();
            //遍历插件列表
            foreach ($dirs as $name) {
                //是否已经安装过
                if (!isset($addons[$name])) {
                    $addons[$name] = $dir_addons_list[$name];
                    if ($addons[$name]) {
                        $addons[$name]['status'] = -1;
                        $addons[$name]['create_time'] = 0;
                        $addons[$name]['update_time'] = 0;
                    }
                }
            }
            return $this->success(['list' => $addons]);
        }

        return view();
    }

    /**
     * 安装
     * @param $name
     * @return \think\Response
     */
    public function install($name = null)
    {
        if (request()->isAjax()) {
            $name = $name ? $name : request()->post("name/s");
            if (!$name) return $this->error('插件名有误');

            $this->model->startTrans();
            try {
                PluginService::install($name);

                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $this->success();
        }
        return $this->error("请求方法错误");
    }

    /**
     * 卸载
     * @param $name
     * @return \think\Response
     */
    public function uninstall($name = null)
    {
        if (request()->isAjax()) {
            $name = $name ? $name : request()->post("name/s");
            if (!$name) return $this->error('插件名有误');

            $this->model->startTrans();
            try {
                PluginService::uninstall($name);

                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $this->success();
        }
        return $this->error("请求方法错误");
    }

    /**
     * 启用
     * @param $name
     * @return \think\Response
     */
    public function enable($name = null)
    {
        if (request()->isAjax()) {
            $name = $name ? $name : request()->post("name/s");
            if (!$name) return $this->error('插件名有误');

            $this->model->startTrans();
            try {
                PluginService::enable($name);

                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $this->success();
        }
        return $this->error("请求方法错误");
    }

    /**
     * 禁用
     * @param $name
     * @return \think\Response
     */
    public function disable($name = null)
    {
        if (request()->isAjax()) {
            $name = $name ? $name : request()->post("name/s");
            if (!$name) return $this->error('插件名有误');

            $this->model->startTrans();
            try {
                PluginService::disable($name);

                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $this->success();
        }
        return $this->error("请求方法错误");
    }

    /**
     * 设置插件页面
     * @param null $name
     * @return \think\Response|\think\response\View
     */
    public function config($name = null)
    {
        $name = $name ? $name : request()->request("name/s");
        if (!$name) return $this->error('插件名有误');
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $name)) return $this->error('插件名称不正确！');
        if (!is_dir(ADDON_PATH . $name)) return $this->error('目录不存在！');
        $info = get_addons_info($name);
        $config = get_addons_config($name);
        if (!$info) return $this->error('配置不存在！');

        if (request()->isPost()) {
            $params = request()->post();
            if ($params) {
                foreach ($config as $k => &$v) {
                    if (isset($params[$v['name']])) {
                        //TODO to be completed
                        if ($v['type'] == 'array') {
                            $params[$v['name']] = is_array($params[$v['name']]) ? $params[$v['name']] : (array)json_decode($params[$v['name']], true);
                            $value = $params[$v['name']];
                        } else {
                            $value = is_array($params[$v['name']]) ? implode(',', $params[$v['name']]) : $params[$v['name']];
                        }
                        $v['value'] = $value;
                    }
                }
                try {
                    //更新配置文件
                    set_addons_fullconfig($name, $config);
                    PluginService::refresh();
                } catch (\Exception $e) {
                    return $this->error($e->getMessage());
                }
            }
            return $this->success('插件配置保存成功！');
        }
        //启用layout
        $this->layout && $this->app->view->engine()->layout($this->layout);
        View::assign('addon', ['info' => $info, 'config' => $config]);
        $configFile = ADDON_PATH . $name . DS . 'config.html';
        $viewFile = is_file($configFile) ? $configFile : '';
        return view($viewFile);
    }
}
